<?php

namespace app\api\controller;

use app\common\exception\BusinessException;
use think\Response;
use think\response\Json;

class Verify extends Base
{
    /**
     * 获取图形验证码
     * @return Response
     */
    public function getCode(): Response
    {
        //外部参数
        $key = $this->request->param('key', '');

        //返回
        return app(\app\api\logic\Verify::class)->getCode($key);
    }

    /**
     * 发送短信验证码
     * @throws BusinessException
     */
    public function sendSmsCode(): Json
    {
        // 请求参数
        $param = $this->request->param();

        // 验证规则
        $rule = [
            'code' => 'require',
            'scene' => 'require',
            'mobile' => 'require',
        ];

        // 错误信息
        $errMsg = [
            'code.require' => '请输入图形验证码',
            'scene.require' => '请选择验证场景',
            'mobile.require' => '请输入手机号码',
        ];

        // 数据验证
        $valRel = $this->validate($param, $rule, $errMsg);
        if ($valRel !== true) {
            throw new BusinessException($valRel);
        }

        // 填充请求IP
        $param['ip'] = $this->request->ip();

        // 提交发送
        app(\app\api\logic\Verify::class)->sendSmsCode($param);

        // 返回
        return $this->response([], 1, '发送成功');
    }

    /**
     * 发送邮件验证码
     * @throws BusinessException
     */
    public function sendMailCode(): Json
    {
        //外部参数
        $param = $this->request->param();
        if (empty($param['action'])) {
            throw new BusinessException('操作方式不得为空');
        }

        //验证规则
        $rule = [
            'key' => 'require',
        ];
        if ($param['action'] != 1) {
            $rule['key'] .= '|email';
        }

        //错误信息
        $errMsg = [
            'key.require' => '邮箱地址不得为空'
        ];
        if ($param['action'] != 1) {
            $errMsg[] = ['key.email' => '邮箱地址不正确'];
        }

        //数据验证
        $valRel = $this->validate($param, $rule, $errMsg);
        if ($valRel !== true) {
            throw new BusinessException($valRel);
        }

        //提交发送
        app(\app\api\logic\Verify::class)->sendMailCode($param);

        //返回
        $text = '验证码已发送到邮箱';
        return $this->response([], 1, $text);
    }
}